package com.example.demo.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;

/**
 * Created by wangyg6 on 2018/10/18.
 */
public class SerializeUtil {
	private static ObjectMapper objMapper = new ObjectMapper();

	static {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		objMapper.setDateFormat(dateFormat);
		objMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		objMapper.enable(SerializationFeature.INDENT_OUTPUT);
		objMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
		objMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT, false);
		objMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
		objMapper.disable(SerializationFeature.CLOSE_CLOSEABLE);
		objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
		objMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		//		objMapper.configure(JsonParser.Feature.IGNORE_UNDEFINED, true);
	}

	public static <T> String serialize(T obj) {
		String result = null;
		try {
			result = objMapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			throw new IllegalStateException(e.getMessage(), e);
		} catch (IOException e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
		return result;
	}

	public static <T> T toBean(String json, Class<T> clazz) throws IOException {
		return !StringUtils.hasText(json) ? null : objMapper.readValue(json, clazz);
	}

	public static <T> T toBean(String json, JavaType javaType) throws IOException {
		return objMapper.readValue(json, javaType);
	}

	
	public static Object buildObj(Class<?> returnType, Type returnGenericType, String param) {
		try {
			if (returnType.equals(String.class)) {
				return param;
			} else {
				if (returnGenericType instanceof ParameterizedType) {
					return objMapper.readValue(param, com.fasterxml.jackson.databind.type.TypeFactory.defaultInstance()
							.constructType(returnGenericType));
				} else {
					return toBean(param, returnType);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException("反序列化http请求结果异常:," + e);
		}
	}
}
